import useStore from '@/store';
import { defineStore } from 'pinia';
import { Profile } from '@/types/user'
import request from '@/utils/request'
import { ApiRes } from '@/types/data';
import { setProfile, getProfile, removeProfile } from '@/utils/storage'
export default defineStore('user', {
  state() {
    return {
      // 个人的用户信息
      profile: getProfile()
    }
  },
  actions: {
    // 用户名+密码登录
    async login(account: string, password: string) {
      const res = await request.post<ApiRes<Profile>>('/login', {
        account,
        password
      })
      console.log('登录的返回个人信息', res);
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 手机号+验证码登录    
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<Profile>>('/login/code', {
        mobile,
        code
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // QQ绑定完成登录
    async qqBindLogin(mobile: string, code: string, openId: string) {
      const res = await request.post<ApiRes<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId
      })
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // qq登录
    async qqLogin(openId: string) {
      const res = await request.post<ApiRes<Profile>>('/login/social', {
        unionId: openId,
        source: 6
      })
      console.log('qq登录返回的结果', res.data);
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 无账号 无绑定 完善信息 进行登录
    async qqPatchLogin(data: any) {
      const res = await request.post<ApiRes<Profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    // 无账号 无绑定 获取验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile
        }
      })
    },
    // 获取手机号验证码
    async sendMobileCode(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },

    // 绑定qq的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    // 退出
    logOut() {
      this.profile = {} as Profile
      removeProfile()
      // 清空购物车
      const { cart } = useStore()
      cart.clearCart()
    }
  }
})